<?php
/**
 * Copyright (c) 2006-2007, Julien PORTALIER
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright    Copyright (c) 2006-2007, Julien PORTALIER
 * @link         http://featherphp.googlecode.com/
 * @license      http://www.opensource.org/licenses/mit-license.php The MIT License
 */

/**
 * Useful functions to manipulates files and filenames.
 */
class Files
{
	static function getExtension($filename)
	{
		return substr(strrchr($filename, '.'), 1);
	}
	
	static function removeExtension($filename)
	{
		return substr($filename, 0, -strlen(strrchr($filename, '.')));
	}
	
	static function copydir($from, $dest)
	{
		if (!is_dir($dest))
			mkdir($dest);
		
		if ($dh = opendir($from))
		{
			while($f = readdir($dh))
			{
				if ($f == '.' || $f == '..')
					continue;
				
				if (is_dir($from.DS.$f))
					self::copydir($from.DS.$f, $dest.DS.$f);
				elseif (is_file($from.DS.$f))
				{
					copy($from.DS.$f, $dest.DS.$f);
					touch($from.DS.$f, filemtime($dest.DS.$f));
				}
			}
			closedir($dh);
		}
	}
	
	static function mkdir($dir, $mode=0755)
	{
		if (is_dir($dir) || @mkdir($dir, $mode))
			return true;
		if (!self::mkdirr(dirname($dir), $mode))
			return false;
		return @mkdir($dir, $mode);
	}
	
	static function rmdir($path, $remove_empty_dir=true)
	{
		if (is_dir($path) and ($handle = opendir($path)))
		{
			while (false !== ($file = readdir($handle)))
			{
				if ($file == '.' or $file == '..')
					continue;
				if (is_dir($path.$file))
					self::rmdirr($path.$file, false);
				else
				{
					if (!unlink($path.$file))
						return false;
				}
			}
			closedir($handle);
			
			if (!rmdir($path))
				return false;
		}
		elseif (file_exists($path))
		{
			if (!unlink($path))
				return false;
		}
		
		if ($remove_empty_dir)
			self::rm_empty_dir(dirname($path).DS);
		
		return true;
	}
	
	static function rm($fname, $rm_empty_dir=true)
	{
		if (is_file($fname) and !unlink($fname))
			return false;
		
		if ($rm_empty_dir)
			self::rm_empty_dir(dirname($fname).DS);
		
		return true;
	}
	
	static function rm_empty_dir($path)
	{
		$files =& glob($path.'*');
		
		if (empty($files))
		{
			if (!rmdir($path))
				return false;
		}
	}
}
?>